package pl.task;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class TaskContentProvider extends ContentProvider
{
    private static final int TASKS = 1;
    private static final int TASK_ID = 2;

    private static final UriMatcher URI_MATCHER;
    private static HashMap<String, String> TASKS_PROJECTION_MAP;
    static
    {
        URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
        URI_MATCHER.addURI(Task.AUTHORITY, "tasks", TASKS);
        URI_MATCHER.addURI(Task.AUTHORITY, "tasks/#", TASK_ID);

        TASKS_PROJECTION_MAP = new HashMap<String, String>();
        TASKS_PROJECTION_MAP.put(Task._ID, Task._ID);
        TASKS_PROJECTION_MAP.put(Task.NAZWA, Task.NAZWA);
        TASKS_PROJECTION_MAP.put(Task.OPIS, Task.OPIS);
    }

    private SQLiteOpenHelper openHelper;

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs)
    {
        final SQLiteDatabase database = openHelper.getWritableDatabase();

        int result;
        switch (URI_MATCHER.match(uri))
        {
            case TASKS:
                result = database.delete(Task.TABLE_NAME, selection, selectionArgs);
                break;
            case TASK_ID:
                final String id = uri.getPathSegments().get(1);
                result = database.delete(Task.TABLE_NAME, Task._ID + "=" + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);

        return result;
    }

    @Override
    public String getType(Uri uri)
    {
        String result = null;

        switch (URI_MATCHER.match(uri))
        {
            case TASKS:
                result = Task.CONTENT_TYPE;
                break;
            case TASK_ID:
                result = Task.CONTENT_ITEM_TYPE;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        return result;
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues)
    {
        // Validate the requested uri
        if (URI_MATCHER.match(uri) != TASKS)
        {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        final ContentValues values = (initialValues != null) ? new ContentValues(initialValues) : new ContentValues();

        if (!values.containsKey(Task.NAZWA))
        {
            values.put(Task.NAZWA, "");
        }
        if (!values.containsKey(Task.OPIS))
        {
            values.put(Task.OPIS, "");
        }

        final SQLiteDatabase database = openHelper.getWritableDatabase();
        final long rowId = database.insert(Task.TABLE_NAME, "", values);
        if (rowId <= 0)
        {
            throw new SQLException("Failed to insert row into " + uri);
        }

        final Uri result = ContentUris.withAppendedId(Task.CONTENT_URI, rowId);

        getContext().getContentResolver().notifyChange(result, null);

        return result;
    }

    @Override
    public boolean onCreate()
    {
        final TaskApplication application = (TaskApplication) getContext().getApplicationContext();
        openHelper = application.getOpenHelper();

        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
    {
/*
        final MatrixCursor result = new MatrixCursor(new String[] {_ID, NAZWA});
        result.addRow(new Object[] {1, "Task_nazwa1"});
        result.addRow(new Object[] {2, "Task_nazwa2"});
        result.addRow(new Object[] {3, "Task_nazwa3"});
        result.addRow(new Object[] {4, "Task_nazwa4"});

        return result;
*/

        final SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
        queryBuilder.setTables(Task.TABLE_NAME);

        switch (URI_MATCHER.match(uri))
        {
            case TASKS:
                queryBuilder.setProjectionMap(TASKS_PROJECTION_MAP);
                break;
            case TASK_ID:
                queryBuilder.setProjectionMap(TASKS_PROJECTION_MAP);
                queryBuilder.appendWhere(Task._ID + "=" + uri.getPathSegments().get(1));
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        final  String orderBy = TextUtils.isEmpty(sortOrder) ? "" : sortOrder;

        final SQLiteDatabase database = openHelper.getReadableDatabase();
        final Cursor result = queryBuilder.query(database, projection, selection, selectionArgs, null, null, orderBy);
        result.setNotificationUri(getContext().getContentResolver(), uri);

        return result;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
    {
        int result;

        final SQLiteDatabase database = openHelper.getWritableDatabase();
        switch (URI_MATCHER.match(uri))
        {
            case TASKS:
                result = database.update(Task.TABLE_NAME, values, selection, selectionArgs);
                break;
    
            case TASK_ID:
                final String id = uri.getPathSegments().get(1);
                result = database.update(Task.TABLE_NAME, values, Task._ID + "=" + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);

        return result;
    }
}
